package com.ftdc.app.lock;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;

public class AbstractQueuedSynchronizerLock {
    private static class Sync extends AbstractQueuedSynchronizer {
        // 判断锁是否被占用
        @Override
        protected boolean tryAcquire(int acquire) {
            return compareAndSetState(0, 1); // 尝试将状态从 0 改为 1
        }

        // 释放锁
        @Override
        protected boolean tryRelease(int release) {
            setState(0); // 将状态设置为 0
            return true;
        }

        // 判断锁是否被占用
        @Override
        protected boolean isHeldExclusively() {
            return getState() == 1;
        }
    }

    private final Sync sync = new Sync();

    // 加锁
    public void lock() {
        sync.acquire(1);
    }

    // 解锁
    public void unlock() {
        sync.release(1);
    }

    public static void main(String[] args) {
        AbstractQueuedSynchronizerLock lock = new AbstractQueuedSynchronizerLock();

        // 创建线程
        Runnable task = () -> {
            lock.lock();
            try {
                // 执行临界区代码
                System.out.println(Thread.currentThread().getName() + " has acquired the lock.");
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            } finally {
                lock.unlock();
                System.out.println(Thread.currentThread().getName() + " has released the lock.");
            }
        };

        // 启动多个线程
        for (int i = 0; i < 3; i++) {
            new Thread(task).start();
        }
    }
}
